<template>
  <el-card class="profile-edit">
    <h2>基本信息</h2>

    <!-- 用户名 -->
    <div class="field-item" @mouseenter="hoveredField = 'username'" @mouseleave="hoveredField = null">
      <label>用户名：</label>
      <span v-if="!editingFields.username">{{ form.username }}</span>
      <el-input
        v-else
        v-model="tempValues.username"
        style="width: 300px; margin-right: 10px"
      />
      <el-button
        v-if="hoveredField === 'username' && !editingFields.username"
        size="small"
        @click="startEdit('username')"
        style="margin-left: 10px"
      >
        修改
      </el-button>
      <div v-if="editingFields.username">
        <el-button size="small" type="primary" @click="confirmSave('username')">确认</el-button>
        <el-button size="small" @click="cancelEdit('username')">取消</el-button>
      </div>
    </div>

    <!-- 昵称 -->
    <div class="field-item" @mouseenter="hoveredField = 'nickname'" @mouseleave="hoveredField = null">
      <label>昵称：</label>
      <span v-if="!editingFields.nickname">{{ form.nickname }}</span>
      <el-input
        v-else
        v-model="tempValues.nickname"
        style="width: 300px; margin-right: 10px"
      />
      <el-button
        v-if="hoveredField === 'nickname' && !editingFields.nickname"
        size="small"
        @click="startEdit('nickname')"
        style="margin-left: 10px"
      >
        修改
      </el-button>
      <div v-if="editingFields.nickname">
        <el-button size="small" type="primary" @click="confirmSave('nickname')">确认</el-button>
        <el-button size="small" @click="cancelEdit('nickname')">取消</el-button>
      </div>
    </div>

    <!-- 密码 -->
    <div class="field-item" @mouseenter="hoveredField = 'password'" @mouseleave="hoveredField = null">
      <label>密码：</label>
      <span v-if="!editingFields.password">******</span>
      <div v-else style="display: flex; flex-direction: column; gap: 8px;">
        <el-input
          v-model="oldPassword"
          type="password"
          show-password
          placeholder="请输入原密码"
          style="width: 300px;"
        />
        <el-input
          v-model="tempValues.password"
          type="password"
          show-password
          placeholder="新密码"
          style="width: 300px;"
        />
        <el-input
          v-model="confirmPassword"
          type="password"
          show-password
          placeholder="确认密码"
          style="width: 300px;"
          @keyup.enter="confirmSave('password')"
        />
        <p v-if="passwordError" style="color: red; font-size: 12px;">{{ passwordErrorMsg }}</p>
      </div>
      <el-button
        v-if="hoveredField === 'password' && !editingFields.password"
        size="small"
        @click="startEdit('password')"
        style="margin-left: 10px"
      >
        修改
      </el-button>
      <div v-if="editingFields.password">
        <el-button size="small" type="primary" @click="confirmSave('password')">确认</el-button>
        <el-button size="small" @click="cancelEdit('password')">取消</el-button>
      </div>
    </div>

    <!-- 邮箱 -->
    <div class="field-item" @mouseenter="hoveredField = 'email'" @mouseleave="hoveredField = null">
      <label>邮箱：</label>
      <span v-if="!editingFields.email">{{ form.email }}</span>
      <el-input
        v-else
        v-model="tempValues.email"
        style="width: 300px; margin-right: 10px"
      />
      <el-button
        v-if="hoveredField === 'email' && !editingFields.email"
        size="small"
        @click="startEdit('email')"
        style="margin-left: 10px"
      >
        修改
      </el-button>
      <div v-if="editingFields.email">
        <el-button size="small" type="primary" @click="confirmSave('email')">确认</el-button>
        <el-button size="small" @click="cancelEdit('email')">取消</el-button>
      </div>
    </div>

    <!-- 手机号 -->
    <div class="field-item" @mouseenter="hoveredField = 'phone'" @mouseleave="hoveredField = null">
      <label>手机号：</label>
      <span v-if="!editingFields.phone">{{ form.phone }}</span>
      <el-input
        v-else
        v-model="tempValues.phone"
        style="width: 300px; margin-right: 10px"
      />
      <el-button
        v-if="hoveredField === 'phone' && !editingFields.phone"
        size="small"
        @click="startEdit('phone')"
        style="margin-left: 10px"
      >
        修改
      </el-button>
      <div v-if="editingFields.phone">
        <el-button size="small" type="primary" @click="confirmSave('phone')">确认</el-button>
        <el-button size="small" @click="cancelEdit('phone')">取消</el-button>
      </div>
    </div>

    <!-- 性别 -->
    <div class="field-item" @mouseenter="hoveredField = 'gender'" @mouseleave="hoveredField = null">
      <label>性别：</label>
      <span v-if="!editingFields.gender">{{ genderMap[form.gender] }}</span>
      <el-radio-group v-else v-model="tempValues.gender" style="min-width: 200px;">
        <el-radio label="男" value="1" >男</el-radio>
        <el-radio label="女" value="0">女</el-radio>
        <el-radio label="保密" value="2">保密</el-radio>
      </el-radio-group>
      <el-button
        v-if="hoveredField === 'gender' && !editingFields.gender"
        size="small"
        @click="startEdit('gender')"
        style="margin-left: 10px"
      >
        修改
      </el-button>
      <div v-if="editingFields.gender">
        <el-button size="small" type="primary" @click="confirmSave('gender')">确认</el-button>
        <el-button size="small" @click="cancelEdit('gender')">取消</el-button>
      </div>
    </div>

    <!-- 头像上传 -->
    <div class="field-item">
      <label>头像：</label>
      <el-upload
        class="avatar-uploader"
        action="/api/user/upload-avatar"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" />
        <el-icon v-else><Plus /></el-icon>
      </el-upload>
    </div>

    <!-- 个人简介 -->
    <div class="field-item" @mouseenter="hoveredField = 'remark'" @mouseleave="hoveredField = null">
      <label>个人简介：</label>
      <span v-if="!editingFields.remark">{{ form.remark }}</span>
      <el-input
        v-else
        v-model="tempValues.remark"
        type="textarea"
        :rows="4"
        style="width: 500px; margin-right: 10px"
      />
      <el-button
        v-if="hoveredField === 'remark' && !editingFields.remark"
        size="small"
        @click="startEdit('remark')"
        style="margin-left: 10px"
      >
        修改
      </el-button>
      <div v-if="editingFields.remark">
        <el-button size="small" type="primary" @click="confirmSave('remark')">确认</el-button>
        <el-button size="small" @click="cancelEdit('remark')">取消</el-button>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserInfo, updateUserInfo } from '@/api/userApi'
import messagePost from '@/utils/message.js'

const genderMap = {
  1: '男',
  0: '女',
  2: '保密'
}

const form = ref({
  username: '',
  nickname: '',
  password: '',
  email: '',
  phone: '',
  gender: '男',
  avatarUrl: '',
  remark: ''
})

const editingFields = ref({})
const tempValues = ref({
  username: '',
  nickname: '',
  password: '',
  email: '',
  phone: '',
  gender: '男',
  remark: ''
})

// 新增：密码相关字段
const oldPassword = ref('')
const confirmPassword = ref('')
const passwordError = ref(false)
const passwordErrorMsg = ref('')

// 当前鼠标悬停字段
const hoveredField = ref(null)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await getUserInfo()
    console.log(data);
    
    form.value = {
      ...form.value,
      ...data
    }
    // 初始化 tempValues
    tempValues.value = { ...form.value }
  } catch (error) {
    messagePost({ message: '获取用户信息失败', type: 'error' })
  }
}

onMounted(() => {
  fetchUserInfo()
})

// 开始编辑字段
const startEdit = (field) => {
  editingFields.value[field] = true
  tempValues.value[field] = form.value[field]
  if (field === 'password') {
    oldPassword.value = ''
    confirmPassword.value = ''
  }
}

// 取消编辑字段
const cancelEdit = (field) => {
  editingFields.value[field] = false
  tempValues.value[field] = form.value[field]
  if (field === 'password') {
    oldPassword.value = ''
    confirmPassword.value = ''
  }
}

// 确认保存字段
const confirmSave = async (field) => {
  if (field === 'password') {
    const newPassword = tempValues.value.password
    const confirmPass = confirmPassword.value
    const oldPass = oldPassword.value

    if (!oldPass.trim()) {
      passwordError.value = true
      passwordErrorMsg.value = '请输入原密码'
      return
    }

    if (newPassword !== confirmPass) {
      passwordError.value = true
      passwordErrorMsg.value = '两次密码不一致'
      return
    }

    passwordError.value = false
    passwordErrorMsg.value = ''

    try {
      await updateUserInfo({
        field: 'password',
        oldPassword: oldPass,
        newPassword: newPassword
      })
      messagePost({ message: '密码已更新', type: 'success' })
      editingFields.value.password = false
    } catch (error) {
      messagePost({ message: '原密码错误或更新失败', type: 'error' })
    }
  } else {
    // 其他字段直接提交
    form.value[field] = tempValues.value[field]

    try {
      await updateUserInfo({
        field,
        value: form.value[field]
      })
      messagePost({ message: `${getFieldLabel(field)} 已更新`, type: 'success' })
      editingFields.value[field] = false
    } catch (error) {
      messagePost({ message: `${getFieldLabel(field)} 更新失败`, type: 'error' })
    }
  }
}

// 字段中文映射
const getFieldLabel = (field) => {
  const labels = {
    username: '用户名',
    nickname: '昵称',
    password: '密码',
    email: '邮箱',
    phone: '手机号',
    gender: '性别',
    remark: '个人简介'
  }
  return labels[field] || field
}

// 头像上传逻辑
const handleAvatarSuccess = (res) => {
  form.value.avatarUrl = res.url
  messagePost({ message: '头像已更新', type: 'success' })
}

const beforeAvatarUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type)
  if (!isValidType) {
    messagePost({ message: '只能上传 JPG/PNG 格式图片!', type: 'error' })
    return false
  }
  return true
}
</script>

<style scoped>
.profile-edit {
  max-width: 900px;
  margin: 20px auto;
}

.field-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  position: relative;
  padding: 5px;
  transition: background-color 0.2s ease;
  min-height: 40px;
}

.field-item:hover {
  background-color: #f9f9f9;
}

label {
  width: 100px;
  font-weight: bold;
  flex-shrink: 0;
}

/* 固定宽度防止抖动 */
.field-item span,
.field-item .el-input,
.field-item .el-radio-group {
  min-width: 200px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}
</style>